<template>
  <div class="course-management">
    <div class="page-header">
      <h2>课程管理</h2>
      <el-button type="primary" @click="handleAddCourse">
        <el-icon><plus /></el-icon>
        添加课程
      </el-button>
    </div>
    
    <!-- 搜索和筛选 -->
    <div class="search-filter">
      <el-input
        v-model="searchQuery"
        placeholder="搜索课程名称、教师"
        prefix-icon="Search"
        style="width: 300px;"
        @keyup.enter="handleSearch"
      >
      </el-input>
      
      <el-select v-model="categoryFilter" placeholder="课程类别" style="width: 150px; margin-left: 16px;">
        <el-option label="全部类别" value=""></el-option>
        <el-option label="必修课" value="required"></el-option>
        <el-option label="选修课" value="elective"></el-option>
        <el-option label="通识课" value="general"></el-option>
      </el-select>
      
      <el-button @click="handleSearch" style="margin-left: 16px;">搜索</el-button>
      <el-button @click="handleReset" style="margin-left: 8px;">重置</el-button>
    </div>
    
    <!-- 课程表格 -->
    <el-card class="table-card" style="margin-top: 16px;">
      <el-table
        v-loading="loading"
        :data="coursesData"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="id" label="课程编号" width="120" sortable></el-table-column>
        <el-table-column prop="name" label="课程名称" width="200" sortable></el-table-column>
        <el-table-column prop="teacher" label="授课教师" width="150"></el-table-column>
        <el-table-column prop="category" label="课程类别" width="120">
          <template #default="scope">
            <el-tag :type="getCategoryType(scope.row.category)">{{ getCategoryText(scope.row.category) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="credits" label="学分" width="80" sortable></el-table-column>
        <el-table-column prop="totalHours" label="总课时" width="100" sortable></el-table-column>
        <el-table-column prop="startDate" label="开始日期" width="150" sortable>
          <template #default="scope">
            <span>{{ formatDate(scope.row.startDate) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="endDate" label="结束日期" width="150" sortable>
          <template #default="scope">
            <span>{{ formatDate(scope.row.endDate) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="课程描述"></el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="scope">
            <el-button type="primary" link @click="handleEditCourse(scope.row)">编辑</el-button>
            <el-button type="danger" link @click="handleDeleteCourse(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    
    <!-- 分页 -->
    <div class="pagination" style="margin-top: 16px;">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    
    <!-- 添加/编辑课程对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
      @close="handleDialogClose"
    >
      <el-form
        ref="courseFormRef"
        :model="courseForm"
        :rules="courseRules"
        label-width="100px"
      >
        <el-form-item label="课程编号" prop="id">
          <el-input v-model="courseForm.id" :disabled="isEditMode"></el-input>
        </el-form-item>
        <el-form-item label="课程名称" prop="name">
          <el-input v-model="courseForm.name"></el-input>
        </el-form-item>
        <el-form-item label="授课教师" prop="teacher">
          <el-input v-model="courseForm.teacher"></el-input>
        </el-form-item>
        <el-form-item label="课程类别" prop="category">
          <el-select v-model="courseForm.category">
            <el-option label="必修课" value="required"></el-option>
            <el-option label="选修课" value="elective"></el-option>
            <el-option label="通识课" value="general"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="学分" prop="credits">
          <el-input v-model.number="courseForm.credits" type="number" min="1" max="10"></el-input>
        </el-form-item>
        <el-form-item label="总课时" prop="totalHours">
          <el-input v-model.number="courseForm.totalHours" type="number" min="16" max="200"></el-input>
        </el-form-item>
        <el-form-item label="开始日期" prop="startDate">
          <el-date-picker
            v-model="courseForm.startDate"
            type="date"
            placeholder="选择日期"
            style="width: 100%;"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="结束日期" prop="endDate">
          <el-date-picker
            v-model="courseForm.endDate"
            type="date"
            placeholder="选择日期"
            style="width: 100%;"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="课程描述" prop="description">
          <el-input v-model="courseForm.description" type="textarea" :rows="3"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveCourse">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { Plus, Search } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

// 搜索和筛选条件
const searchQuery = ref('')
const categoryFilter = ref('')

// 表格数据
const coursesData = ref([])
const loading = ref(false)
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const selectedCourses = ref([])

// 对话框相关
const dialogVisible = ref(false)
const isEditMode = ref(false)
const dialogTitle = computed(() => isEditMode.value ? '编辑课程' : '添加课程')
const courseFormRef = ref(null)
const courseForm = reactive({
  id: '',
  name: '',
  teacher: '',
  category: 'required',
  credits: '',
  totalHours: '',
  startDate: '',
  endDate: '',
  description: ''
})

// 表单验证规则
const courseRules = {
  id: [
    { required: true, message: '请输入课程编号', trigger: 'blur' },
    { pattern: /^[A-Za-z0-9]+$/, message: '课程编号只能包含字母和数字', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入课程名称', trigger: 'blur' },
    { min: 2, max: 100, message: '课程名称长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  teacher: [
    { required: true, message: '请输入授课教师', trigger: 'blur' },
    { min: 2, max: 20, message: '教师姓名长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择课程类别', trigger: 'change' }
  ],
  credits: [
    { required: true, message: '请输入学分', trigger: 'blur' },
    { type: 'number', min: 1, max: 10, message: '学分在 1 到 10 之间', trigger: 'blur' }
  ],
  totalHours: [
    { required: true, message: '请输入总课时', trigger: 'blur' },
    { type: 'number', min: 16, max: 200, message: '总课时在 16 到 200 之间', trigger: 'blur' }
  ],
  startDate: [
    { required: true, message: '请选择开始日期', trigger: 'change' }
  ],
  endDate: [
    { required: true, message: '请选择结束日期', trigger: 'change' },
    {
      validator: (rule, value, callback) => {
        if (value && courseForm.startDate && new Date(value) < new Date(courseForm.startDate)) {
          callback(new Error('结束日期不能早于开始日期'))
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ]
}

// 获取课程类别文本
const getCategoryText = (category) => {
  const categoryMap = {
    'required': '必修课',
    'elective': '选修课',
    'general': '通识课'
  }
  return categoryMap[category] || category
}

// 获取课程类别标签类型
const getCategoryType = (category) => {
  const typeMap = {
    'required': 'primary',
    'elective': 'success',
    'general': 'warning'
  }
  return typeMap[category] || 'default'
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN')
}

// 加载课程数据
const loadCourses = async () => {
  loading.value = true
  try {
    // 真实的API调用
    const response = await axios.get('/api/courses', {
      params: {
        page: currentPage.value,
        pageSize: pageSize.value,
        keyword: searchQuery.value,
        category: categoryFilter.value
      }
    })
    coursesData.value = response.data.data
    total.value = response.data.total
  } catch (error) {
    console.error('加载课程数据失败:', error)
    ElMessage.error('加载课程数据失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
  loadCourses()
}

// 处理重置
const handleReset = () => {
  searchQuery.value = ''
  categoryFilter.value = ''
  currentPage.value = 1
  loadCourses()
}

// 处理分页大小变化
const handleSizeChange = (newSize) => {
  pageSize.value = newSize
  loadCourses()
}

// 处理页码变化
const handleCurrentChange = (newPage) => {
  currentPage.value = newPage
  loadCourses()
}

// 处理选择变化
const handleSelectionChange = (selection) => {
  selectedCourses.value = selection
}

// 打开添加课程对话框
const handleAddCourse = () => {
  isEditMode.value = false
  // 重置表单
  Object.keys(courseForm).forEach(key => {
    courseForm[key] = key === 'category' ? 'required' : ''
  })
  dialogVisible.value = true
}

// 打开编辑课程对话框
const handleEditCourse = (row) => {
  isEditMode.value = true
  // 填充表单
  Object.assign(courseForm, row)
  dialogVisible.value = true
}

// 保存课程
const handleSaveCourse = async () => {
  try {
    await courseFormRef.value.validate()
    
    // 真实的API调用
    if (isEditMode.value) {
      await axios.put(`/api/courses/${courseForm.id}`, courseForm)
      ElMessage.success('课程更新成功')
    } else {
      await axios.post('/api/courses', courseForm)
      ElMessage.success('课程添加成功')
    }
    
    dialogVisible.value = false
    loadCourses()
  } catch (error) {
    console.error('保存课程数据失败:', error)
    ElMessage.error('保存课程数据失败，请稍后重试')
  }
}

// 删除课程
const handleDeleteCourse = (id) => {
  ElMessageBox.confirm(
    '确定要删除这个课程吗？删除后将无法恢复。',
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(async () => {
      // 真实的API调用
      await axios.delete(`/api/courses/${id}`)
      ElMessage.success('课程删除成功')
      loadCourses()
    })
    .catch(() => {
      // 用户取消删除
    })
}

// 关闭对话框
const handleDialogClose = () => {
  if (courseFormRef.value) {
    courseFormRef.value.resetFields()
  }
}

// 初始加载数据
loadCourses()
</script>

<style scoped>
.course-management {
  height: 100%;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.page-header h2 {
  margin: 0;
  font-size: 20px;
  color: #333;
}

.search-filter {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}

.pagination {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

@media (max-width: 768px) {
  .search-filter {
    flex-direction: column;
    align-items: stretch;
    gap: 12px;
  }
  
  .search-filter .el-input,
  .search-filter .el-select {
    width: 100% !important;
  }
  
  .search-filter .el-button {
    margin-left: 0 !important;
  }
  
  .page-header {
    flex-direction: column;
    align-items: stretch;
    gap: 12px;
  }
}
</style>